#include <all.h>

static uint32_t sys_work_time = 0;

uint32_t sys_get_time_ms()
{
	return sys_work_time;
}

static void ticker_time_cb(ticker_event_t *e)
{
	sys_work_time++;
	btn_tic_ms(1);
}

static void sys_init_anim()
{
	int8_t i;

	for (i = 64; i > 24; i -= 2)
	{
		oled_fill_full_screen(0);
		oled_set_position(32, i);
		oled_draw_str("启凡科创", 1);
		oled_push_area(30, 0, 64, 64);
	}
	delay(1000);

	for (i = 24; i > -16; i -= 2)
	{
		oled_fill_full_screen(0);
		oled_set_position(32, i);
		oled_draw_str("启凡科创", 1);
		oled_push_area(30, 0, 64, 64);
	}
	sys_reset();

	oled_fill_full_screen(0);
	oled_set_position(16, 24);
	oled_set_auto_line(auto_line_enable);
	oled_draw_str("长按进行测试", 1);
	oled_push_screen();
}
void io_init()
{
	/*
M1  M0
0   0 准双向
0   1 推挽
1   0 高阻
1   1 开漏
*/

	P0PU |= 0Xe0; // 使能IIC/pass测试指示灯 4.7k上拉
	P0 = 0x00;
	P0M1 = 0X01;
	P0M0 = 0x1e;

	P1 = 0x00;
	P1M1 = 0Xfc;
	P1M0 = 0X03;

	P2 = 0x00; // 0110 1010   1001 0101
	P2M1 = 0x6a;
	P2M0 = 0X95;

	P3 = 0x03; // 1010 1000   0101 0100
	P3M1 = 0xa8;
	P3M0 = 0X54;

	P4 = 0x00; // 1100 1010
	P4M1 = ~0Xca;
	P4M0 = 0Xca;

	P5 = 0X00; // 0000 0110
	P5PU |= 0X04;
	P5M1 = 0x10;
	P5M0 = 0X06; // P5M0|=0X04;

	P6 = 0X82;
	//	P6PU|=0X05;      0000 0000      0111 1101
	P6M1 = 0X00;
	P6M0 = 0X7d; // 0111 1101

	P7 = 0X00; //  1010 0101
	P7M1 = ~0Xa5;
	P7M0 = 0Xa5;
}

static uint32_t timer_get_count_cb()
{
	return (uint32_t)timer_get_count(ticker_timer);
}

static void timer_cb()
{
	ticker_heartbeat_ms(1);
	download_chek_loop();
}

void uart_putchar(char dat)
{
	serial_write(uart1, dat);
}

void oled_putchar(char dat)
{
	oled_draw_char(dat, 1);
}

void system_init()
{

	io_init();

	gpio_mode(key_down, INPUT_PULLUP);
	gpio_mode(key_up, INPUT_PULLUP);

	timer_config_time(ticker_timer, mcu_sys_clk, 1000);
	timer_attach(ticker_timer, timer_cb);
	timer_begin(ticker_timer);

	myprintf_attach(uart_putchar);
	serial_begin(uart1, timer1, mcu_sys_clk, uart_band);

	ticker_attach_timer_count_cb(timer_get_count_cb, count_up);
	ticker_attch_ms(1, ticker_time_cb, 0, NULL);

	btn_attach_read_io_func(gpio_read);
	btn_attach(key_down, 0);
	btn_attach(key_up, 0);

	gpio_mode(06, OUTPUT_PULLUP);
	gpio_mode(07, OUTPUT_PULLUP);

	delay(100);

	oled_begin();
	oled_set_font_size(2);

	delay(10);
	sys_init_anim();
	adc_init();

	pwm_init();
}
